package com.istudy.service.imp;

import com.istudy.dao.BaseDao;
import com.istudy.dao.interfaces.WatchDao;
import com.istudy.dao.impl.WatchDaoImpl;
import com.istudy.entity.User;
import com.istudy.entity.Watch;
import com.istudy.service.interfaces.WatchService;
import com.istudy.utils.Page;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class WatchServiceImpl implements WatchService {
    @Override
    public List<Watch> getWatch(HttpServletRequest request , int num) {
        Connection connection = null;
        Page page=new Page();
        List<Watch> list = new ArrayList<>();
        User user=(User)request.getSession().getAttribute("user");
        try {
            connection = BaseDao.getConnection();
           WatchDao watchDao = new WatchDaoImpl();
            if (num!=0){
                page.setPageNo(num-1);
            }
            page.setCount(watchDao.getCount(user));
            list= watchDao.getlistByUserID(user,page);
            request.setAttribute("page",page);
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 删除播放记录
     *
     * @param request
     * @return
     */
    @Override
    public boolean delWatch(HttpServletRequest request) {
        Connection connection = null;
      int i=-1;
      boolean b=false;
      int id=Integer.parseInt(request.getParameter("id"));
        try {
            connection = BaseDao.getConnection();
            WatchDao watchDao = new WatchDaoImpl();
            i= watchDao.delWatch(id);
            connection.close();
            if(i>0){
                b=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    /**
     * 新增播放记录
     *
     * @param watch
     * @return
     */
    @Override
    public boolean insertWatch(Watch watch) {
        Connection connection = null;
        int count = 0;
        boolean flag = false;
        try {
            connection = BaseDao.getConnection();
           WatchDao watchDao = new WatchDaoImpl();
            count = watchDao.insertWatch(watch);
            if(count > 0){
                flag = true;
            }
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }
}
